SpringBoot Kotlin热部署采坑

使用Kotlin写SpringBoot时遇到了一些小坑,在这里分享下。

热部署原理

SpringBoot使用两个类加载器实现热部署(restart)。

​ Base ClassLoader:加载不变的类,比如三方库jar

​ Restart ClassLoader:用于加载开发过程中的类

​ 当应用重启时,restart classloader就会被丢弃,重新创建一个。因为base classloader中的类不需要重新编译加载,所以这种启动方式比”冷启动”要快。

​ 如果这种启动方式还嫌不够快或是遇到了一些类加载问题,可以考虑使用例如JRebel等方法实现重新加载。

1
2
3
4
5
Restart vs Reload

The restart technology provided by Spring Boot works by using two classloaders. Classes that do not change (for example, those from third-party jars) are loaded into a base classloader. Classes that you are actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts”, since the base classloader is already available and populated.

If you find that restarts are not quick enough for your applications or you encounter classloading issues, you could consider reloading technologies such as JRebel from ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading.

热部署devtools不生效

​ 开发过SpringBoot项目的小伙伴都知道使用devtools就能实现项目热部署,不需要每次改动都要重启项目。

​ 常规配置devtools比较简单,只需要在pom.xml文件中添加devtools依赖即可(maven构建方式)

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

​ 但是,如果项目使用Kotlin作为开发语言,只添加了上述配置并不能生效,即便修改文件后控制台也显示热部署。要想生效,还需要在IDE(Intellj)加上如下两个配置:

1 - Enable Automake from the compiler
  • Press: ctrl + shift + A (For Mac ⌘ + shift + A)
  • Type: make project automatically
  • Hit: Enter
  • Enable Make Project automatically feature
2 - Enable Automake when the application is running
  • Press: ctrl + shift + A (For Mac ⌘ + shift + A)
  • Type: Registry
  • Find the key compiler.automake.allow.when.app.running and enable it or click the checkbox next to it

重启项目即可。

参考

Developer Tools

Intellij IDEA Java classes not auto compiling on save